package cn.catsdad.util;

import cn.catsdad.constant.ICommonWarningType;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.core.env.Environment;

import java.util.HashMap;
import java.util.Map;

/**
 * 环境工具
 *
 * @author xuyl
 * @version 1.0 2024/5/26
 */
@SuppressWarnings({ICommonWarningType.UNUSED, ICommonWarningType.UNCHECKED})
public class EnvironmentUtil {

    @Data
    @Accessors(chain = true)
    public static class PropertyParam<T> {
        private String key;
        private Class<T> valueType;
        private T defaultValue;

        public Class<T> getValueType() {
            if (this.valueType == null) {
                this.valueType = (Class<T>) defaultValue.getClass();
            }
            return valueType;
        }
    }

    public static <T> T getProperty(PropertyParam<T> param) {
        if (param != null) {
            Environment environment = SpringContextUtil.getContext().getEnvironment();
            return environment.getProperty(param.key, param.getValueType(), param.defaultValue);
        }
        return null;
    }

    @SafeVarargs
    public static <T> Map<String, T> getProperties(PropertyParam<T>... params) {
        Map<String, T> result = new HashMap<>();
        if (StringUtil.isNotEmpty(params)) {
            Environment environment = SpringContextUtil.getContext().getEnvironment();
            for (PropertyParam<T> param : params) {
                result.put(param.key, environment.getProperty(param.key, param.getValueType(), param.defaultValue));
            }
        }
        return result;
    }

}
